import {request, streamRequest} from '@/utils/request';

const BASE_URL = 'http://127.0.0.1:8080';

// 用于管理当前的 EventSource 连接
let currentEventSource: any = null;

// 用户相关接口
export const userApi = {
    // 登录接口
    login: (email: string, password: string) => {
        return request({
            url: `/user/login`,
            method: 'POST',
            data: { email, password }
        });
    },
    // 注册接口
    register: (email: string, password: string) => {
        return request({
            url: `/user/register`,
            method: 'POST',
            data: { email, password }
        });
    }
};

// 文件上传相关接口
export const fileApi = {
    // 单文件上传，返回图片URL字符串
    upload: (file: File) => {
        const fd = new FormData();
        fd.append('file', file);
        return request<string>({
            url: `/file/upload`,
            method: 'POST',
            data: fd,
            header: { 'Content-Type': 'multipart/form-data' }
        });
    },
    // 多文件上传，后端通常返回逗号分隔的URL字符串或字符串数组
    uploads: (files: File[]) => {
        const fd = new FormData();
        files.forEach(f => fd.append('files', f));
        return request<string | string[]>({
            url: `/file/uploads`,
            method: 'POST',
            data: fd,
            header: { 'Content-Type': 'multipart/form-data' }
        });
    }
};

// 验证码相关接口
export const verifyCodeApi = {
    // 发送验证码
    sendVerifyCode: (email: string) => {
        return request({
            url: `/mail/sendVerifyCode`,
            method: 'GET',
            params: { email }
        });
    },
    // 验证验证码
    verifyCode: (email: string, inputCode: string) => {
        return request({
            url: `/mail/verifyCode`,
            method: 'GET',
            params: { email, inputCode }
        });
    }
};

// LLM相关接口
export const llmApi = {
    // 流式聊天接口（GET请求）
    chatStream: (
        sessionId: string,
        message: string,
        userID: number,
        onMessage: (chunk: string) => void,
        onComplete?: () => void,
        onError?: (error: any) => void
    ) => {
        // 如果有旧连接，先关闭
        if (currentEventSource) {
            currentEventSource();
            currentEventSource = null;
        }

        // 创建新连接并保存清理函数
        currentEventSource = streamRequest(
            {
                url: `/llm/chat`,
                method: 'GET',
                params: {
                    sessionId,
                    message,
                    userID
                }
            },
            onMessage,
            () => {
                // 完成后清空引用
                currentEventSource = null;
                onComplete?.();
            },
            (error) => {
                // 错误后清空引用
                currentEventSource = null;
                onError?.(error);
            }
        );

        return currentEventSource;
    },

    clear: (sessionId: string) => {
        return request({
            url: `/llm/clear`,
            method: 'GET',
            params: { sessionId }
        });
    },

    // 生成标题接口
    generateTitle: (content: string, userId: number) => {
        return request<string>({
            url: `/llm/title`,
            method: 'GET',
            params: { content, userId }
        });
    },

    // 获取会话列表接口
    getSession: (userId: number) => {
        return request<Array<{
            sessionId: string;
            userId: number;
            title: string;
            createTime: string;
        }>>({
            url: `/llm/getSession`,
            method: 'GET',
            params: { userId }
        });
    },

    // 获取对话记录接口
    getConversation: (sessionId: string) => {
        return request<Array<{
            messageId: string;
            sessionId: string;
            userId: number;
            role: string;
            message: string;
            createdTime: string;
        }>>({
            url: `/llm/getConversation`,
            method: 'GET',
            params: { sessionId }
        });
    }
};

// 文章相关接口
export interface EssayDTO {
    eId: number;
    uId?: number;
    title: string;
    content: string;
    status?: string;
    images?: string | string[];
    createTime?: string;
    likeCount?: number | null;
    commentCount?: number | null;
    types?: Array<string | { tName?: string; tname?: string; name?: string }>;
    user?: {
        userId?: number;
        userName?: string;
        avatar?: string;
        [key: string]: any;
    };
    // 兼容旧字段
    userName?: string;
    avatar?: string;
    [key: string]: any;
}

// 文章类型相关接口
export interface TypeDTO {
    tId: number;
    tName: string;
}

export const typeApi = {
    // 获取文章类型列表接口
    listType: () => {
        return request<TypeDTO[]>({
            url: `/type/list`,
            method: 'GET'
        });
    }
};

export const articleApi = {
    // 获取文章列表接口
    listEssay: (eIds: string[] = [], size: number = 12, type?: string, search?: string) => {
        // 构建查询参数
        const params: Record<string, any> = {};

        // size参数
        if (size !== undefined && size !== null) {
            params.size = size;
        }

        // 处理eIds数组参数：Spring Boot的List参数需要多个同名参数
        // 后端应该使用：@RequestParam("eIds") List<String> eIds
        // 注意：如果eIds为空数组，不传递这个参数，避免后端绑定错误
        if (eIds && eIds.length > 0) {
            params.eIds = eIds; // 直接传递数组，request.ts会处理为多个同名参数 ?eIds=1&eIds=2&eIds=3
        }

        if (type) {
            params.type = type;
        }

        if (search) {
            params.search = search;
        }

        return request<EssayDTO[]>({
            url: `/essay/listEssay`,
            method: 'GET',
            params
        });
    },

    // 获取文章详情
    getEssayById: (eId: number | string) => {
        return request<EssayDTO>({
            url: `/essay/getEssayById`,
            method: 'GET',
            params: { eId }
        });
    },

    // 发布文章（GET，携带查询参数 uId、tIds、以及文章字段）
    addEssay: (payload: {
        uId: number;
        title: string;
        content: string;
        status?: string;
        images?: string | string[];
        tIds?: Array<number | string>;
        createTime?: string;
    }) => {
        let images: any = payload.images;
        if (Array.isArray(images)) {
            images = images.join(',');
        }
        const params: Record<string, any> = {
            uId: payload.uId,
            title: payload.title,
            content: payload.content,
            status: payload.status,
            tIds:payload.tIds,
            images: images,
            // 兼容后端若按 essay.* 绑定
            'essay.title': payload.title,
            'essay.content': payload.content,
            'essay.status': payload.status,
            'essay.images': images
        };
        return request<void>({
            url: `/essay/addEssay`,
            method: 'GET',
            params
        });
    }
};
